package com.demo.utils;

import com.demo.entity.ChatMeg;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.util.LinkedList;
import java.util.List;
@Component
/**
 * 持久化，保存聊天记录，实现ChatMemoryStore接口，保存到mongoDB数据库中
 */
public class MongoDBChatMemoryStore implements ChatMemoryStore {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    /**
     * 根据o从指定的ChatMemoryStore中获取消息
     */
    public List<ChatMessage> getMessages(Object o) {
        Criteria criteria = Criteria.where("userId").is(o);
        Query query = new Query(criteria);
        ChatMeg chatMsg = mongoTemplate.findOne(query, ChatMeg.class);
        if(chatMsg == null) {
            return new LinkedList<>();
        }
        return ChatMessageDeserializer.messagesFromJson(chatMsg.getContent());
    }
    @Override
    /**
     * 根据o，更新存储的消息
     */
    public void updateMessages(Object o, List<ChatMessage> list) {
        Criteria criteria = Criteria.where("userId").is(o);
        Query query = new Query(criteria);
        Update update = new Update();
        update.set("content", ChatMessageSerializer.messagesToJson(list));
        mongoTemplate.upsert(query, update, ChatMeg.class);

    }
    @Override
    /**
     *根据o删除存储的消息
     */
    public void deleteMessages(Object o) {
        Criteria criteria = Criteria.where("userId").is(o);
        Query query = new Query(criteria);
        mongoTemplate.remove(query, ChatMeg.class);
    }
}
